<template>
  <a-spin :loading="contentLoading" tip="加载中..." style="width: 100%; height: 100%">
    <div class="page-container revenue-summary-container">
      <!-- 顶部tabs -->
      <div class="revenue-summary-header">
        <!-- tabs -->
        <div class="revenue-summary-tabs">
          <div
            class="revenue-summary-tabs-item"
            @click="onTabsClick(index)"
            :class="{ active: activeIndex == index }"
            v-for="(tab, index) in tabs"
            :key="index"
          >
            <img :src="activeIndex == index ? tab.icon_active : tab.icon" />
            {{ tab.label }}</div
          >
          <!-- 数据更新时间 -->
          <div class="update-time" v-show="updateTime">数据更新时间：{{ updateTime }}</div>
        </div>
        <!-- 筛选条件 -->
        <summary-nav-filter class="revenue-summary-filter" ref="summaryNavFilterRef" @change="filterChange" />
        <!-- 分割线 -->
        <div class="spliter"></div>
      </div>
      <!-- 内容 -->
      <div class="w-full h-full" style="overflow: hidden">
        <!-- 营收数据汇总 -->
        <a-scrollbar
          v-if="activeIndex == 0"
          ref="scrollbarRef"
          :outer-style="{ height: '100%', width: '100%', 'overflow-x': 'hidden' }"
          style="height: 100%; overflow-y: auto; overflow-x: hidden"
          @scroll="onScroll"
        >
          <div class="revenue-summary-content">
            <total ref="moduleRef" :refreshUpdateTime="refreshUpdateTime" @loadDataComplete="loadDataComplete" />
          </div>
        </a-scrollbar>
        <!-- 总资产 -->
        <a-scrollbar
          v-if="activeIndex == 1"
          ref="scrollbarRef"
          :outer-style="{ height: '100%', width: '100%', 'overflow-x': 'hidden' }"
          style="height: 100%; overflow-y: auto; overflow-x: hidden"
          @scroll="onScroll"
        >
          <div class="revenue-summary-content">
            <asset
              ref="moduleRef"
              :nav2WithCode="nav2WithCode"
              :refreshUpdateTime="refreshUpdateTime"
              @loadDataComplete="loadDataComplete"
            />
          </div>
        </a-scrollbar>
        <!-- 总收入 -->
        <a-scrollbar
          v-if="activeIndex == 2"
          ref="scrollbarRef"
          :outer-style="{ height: '100%', width: '100%', 'overflow-x': 'hidden' }"
          style="height: 100%; overflow-y: auto; overflow-x: hidden"
          @scroll="onScroll"
        >
          <div class="revenue-summary-content">
            <income
              ref="moduleRef"
              :nav2WithCode="nav2WithCode"
              :refreshUpdateTime="refreshUpdateTime"
              @loadDataComplete="loadDataComplete"
            />
          </div>
        </a-scrollbar>
        <!-- 总支出 -->
        <a-scrollbar
          v-if="activeIndex == 3"
          ref="scrollbarRef"
          :outer-style="{ height: '100%', width: '100%', 'overflow-x': 'hidden' }"
          style="height: 100%; overflow-y: auto; overflow-x: hidden"
          @scroll="onScroll"
        >
          <div class="revenue-summary-content">
            <expend
              ref="moduleRef"
              :nav2WithCode="nav2WithCode"
              :refreshUpdateTime="refreshUpdateTime"
              @loadDataComplete="loadDataComplete"
            />
          </div>
        </a-scrollbar>
      </div>
    </div>
  </a-spin>
</template>
<script setup lang="ts" name="revenueSummary">
  import { ref, provide, onActivated, nextTick } from 'vue'
  import summaryNavFilter from './components/summary-nav-filter.vue'
  // modules
  import total from './modules/total.vue'
  import asset from './modules/asset.vue'
  import income from './modules/income.vue'
  import expend from './modules/expend.vue'
  import { nav2WithCode as nav2WithCodeFun } from './utils/nav2Helper'
  import useNavigate from '@/hooks/useNavigate'
  const { redirectTo } = useNavigate()
  import dayjs from 'dayjs'

  const scrollbarRef = ref<HTMLElement | null>(null)
  /**
   * 根据图标名称获取图标的真实URL
   *
   * @param {string} icon - 图标名称，不包含文件扩展名
   * @returns {string} 图标的真实URL
   */
  const getUrl = (icon: string) => {
    return new URL(`/src/assets/revenue/${icon}.png`, import.meta.url).href
  }
  // tabs
  const tabs = ref([
    { label: '营收汇总', loaded: false, icon: getUrl('summary'), icon_active: getUrl('summary_active') },
    { label: '总资产', loaded: false, icon: getUrl('asset'), icon_active: getUrl('asset_active') },
    { label: '总收入', loaded: false, icon: getUrl('income'), icon_active: getUrl('income_active') },
    { label: '总支出', loaded: false, icon: getUrl('expend'), icon_active: getUrl('expend_active') },
  ])
  // 数据更新时间
  const updateTime = ref('')
  // 当前默认选中的哪个 tab
  const activeIndex = ref(0)
  /**
   * tabs 切换
   * @param index 点击的 tab 的 index
   */
  const summaryNavFilterRef = ref()
  const onTabsClick = (index: number) => {
    if (activeIndex.value != index) {
      scrollPosition.value = 0
      // 设置头部阴影样式
      setHeaderShadow()
      activeIndex.value = index
      tabs.value[activeIndex.value].loaded = false
      summaryNavFilterRef.value.tabChangeFn(index)
    }
  }
  // 条件筛选
  const queryParam = ref({})
  provide('queryParam', queryParam)
  // 页面跳转函数
  const nav2WithCode = (code: string, extra: any) => {
    nav2WithCodeFun(code, extra, queryParam.value, redirectTo)
  }
  // 更新数据更新时间
  const refreshUpdateTime = (time) => {
    updateTime.value = time
  }
  // 页面加载完成
  const loadDataComplete = () => {
    contentLoading.value = false
    tabs.value[activeIndex.value].loaded = true
  }
  // 设置头部阴影样式 直接查找dom设置效果会流畅一些
  const setHeaderShadow = () => {
    const header = document.querySelector('.revenue-summary-header') as HTMLElement | null
    if (header) {
      if (scrollPosition.value > 0) {
        header.style.setProperty('box-shadow', '0 0px 20px 0 rgb(0 0 0 / 5%)')
      } else {
        header.style.setProperty('box-shadow', 'none')
      }
    }
  }
  // 滚动位置
  const scrollPosition = ref(0)
  // 处理滚动事件，更新滚动位置
  const onScroll = (ev: Event) => {
    const target = ev.target as HTMLElement | null
    if (target) {
      scrollPosition.value = target.scrollTop
      // 设置头部阴影样式
      setHeaderShadow()
    }
  }

  // refs
  const moduleRef = ref()
  const contentLoading = ref(false)
  /**
   * 筛选发生变化
   * @param val
   * @param isFirstLoad 是否是初次加载
   */
  const filterChange = (val: any, isFirstLoad: any) => {
    queryParam.value = val
    if (!isFirstLoad) {
      nextTick(() => {
        updateModule()
      })
    }
  }

  // 触发模块更新
  const updateModule = () => {
    if (tabs.value[activeIndex.value].loaded) {
      contentLoading.value = true
    }
    const param: any = {
      orderTimeQueryType: queryParam.value.orderTimeQueryType,
      startTime: dayjs(queryParam.value.startTime).format('YYYY-MM-DD 00:00:00'),
      endTime: dayjs(queryParam.value.endTime).format('YYYY-MM-DD 23:59:59'),
      selectDateType: queryParam.value.selectDateType,
    }
    // 总支出：门店下拉读取的是机构列表
    if (activeIndex.value == 3) {
      if (queryParam.value.orgIdList && queryParam.value.orgIdList.length > 0) {
        param.orgIdList = queryParam.value.orgIdList
      }
    } else {
      if (queryParam.value.siteIdList && queryParam.value.siteIdList.length > 0) {
        param.siteIdList = queryParam.value.siteIdList
      }
    }
    if (moduleRef.value && moduleRef.value.loadData) moduleRef.value.loadData(param)
  }

  // 激活时更新数据
  onActivated(() => {
    if (scrollbarRef.value) {
      scrollbarRef.value.scrollTo({ top: scrollPosition.value })
    }
    updateModule()
  })
</script>
<style lang="less" scoped>
  .revenue-summary-container {
    height: 100%;
    display: flex;
    flex-direction: column;

    padding: 0;
  }
  .revenue-summary-header {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    padding: 20px 20px 0;
    background-color: #fff;
    .revenue-summary-tabs {
      margin-bottom: 20px;
      display: flex;
      .revenue-summary-tabs-item {
        height: 32px;
        line-height: 30px;
        padding: 0 12px;
        border-radius: 2px 2px 2px 2px;
        border: 1px solid #3370ff;
        font-size: 14px;
        color: #3370ff;
        cursor: pointer;
        display: flex;
        align-items: center;
        img {
          width: 16px;
          height: 16px;
          margin-right: 5px;
        }
      }
      .revenue-summary-tabs-item + .revenue-summary-tabs-item {
        margin-left: 16px;
      }
      .revenue-summary-tabs-item.active {
        background-color: #3370ff;
        color: #fff;
      }
      .update-time {
        font-size: 12px;
        color: #919aa5;
        height: 32px;
        line-height: 32px;
        margin-left: 12px;
      }
    }
    .revenue-summary-filter {
      margin-bottom: 20px;
    }
  }
  .spliter {
    width: 100%;
    height: 1px;
    background: #f2f3f5;
  }

  .revenue-summary-content {
    width: 100%;
    background-color: #fff;
    padding: 0 20px 20px;
  }
</style>
